package com.yswee.mallnavi.activity.version;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.core.content.FileProvider;

import com.ys.rkapi.MyManager;
import com.yswee.framework.Application;
import com.yswee.framework.manager.ActivityManager;
import com.yswee.framework.net.ITask;
import com.yswee.framework.net.rbd.RBDCallback;
import com.yswee.framework.net.rbd.RBDEntity;
import com.yswee.framework.net.rbd.RBDFactory;
import com.yswee.framework.utils.DialogUtils;
import com.yswee.framework.utils.FileUtils;
import com.yswee.framework.utils.PackageUtils;
import com.yswee.framework.utils.ViewInject;
import com.yswee.framework.widget.MToast;
import com.yswee.mallnavi.R;
import com.yswee.mallnavi.activity.SplashActivity;
import com.yswee.mallnavi.activity.base.BaseActivity;
import com.yswee.mallnavi.context.ContextConstant;
import com.yswee.mallnavi.entity.common.VersionEntity;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.DecimalFormat;

public class UpgradeActivity extends BaseActivity {

    private static final int RESTARTAPP_DELAY = 60000;

    @ViewInject
    protected ProgressBar pbprogress;
    @ViewInject
    protected TextView tvsize;
    @ViewInject
    protected TextView tvpercent;

    private VersionEntity mVersionEntity;
    private DecimalFormat mDecimalFormat;

    @Override
    protected boolean isDialogTheme() {
        return true;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_upgrade);
    }

    @Override
    protected void onQueryArguments(Intent intent) {
        super.onQueryArguments(intent);
        mVersionEntity = (VersionEntity) intent.getSerializableExtra(ContextConstant.INTENT_DATA);
    }

    @Override
    protected void onBindListener() {
        super.onBindListener();
    }

    @Override
    protected void onApplyData() {
        super.onApplyData();
        startDownloadApk();
    }

    private void startDownloadApk() {
        final String apkFileName = getApkFileName();
        File file = new File(apkFileName);
        if (file != null && file.length() > 0) {
            installApkFileUseSdk(apkFileName);
            return;
        }
        RBDEntity entity = new RBDEntity();
        entity.setBaseUrl(mVersionEntity.url);
        entity.setFilePath(apkFileName);
        ITask task = RBDFactory.get().createRBD(entity, new RBDCallback() {
            @Override
            public void onFinish(RBDEntity entity) {
                installApkFileUseSdk(apkFileName);
            }

            @Override
            public void onError(RBDEntity entity) {
                DialogUtils.showConfirmDialog(UpgradeActivity.this,
                        getString(R.string.upgrade_download_error),
                        new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                startDownloadApk();
                            }
                        },
                        new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                finish();
                            }
                        });
            }

            @Override
            public void onDownloadProgress(RBDEntity entity) {
                super.onDownloadProgress(entity);
                long total = entity.getTotalSize();
                long current = entity.getCurentSize();
                int percent = (int) (current * 100 / total);
                if (percent > 100) {
                    percent = 100;
                }
                if (mDecimalFormat == null) {
                    mDecimalFormat = new DecimalFormat("0.0");
                }
                pbprogress.setProgress(percent);
                tvsize.setText(mDecimalFormat.format(current * 1.0f / 1024 / 1024) + "mb/" +
                        mDecimalFormat.format(total * 1.0f / 1024 / 1024) + "mb");
                tvpercent.setText(percent + "%");
            }
        });
        task.excute();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private String getApkFileName() {
        return FileUtils.getCachePath() + File.separator +
                FileUtils.APKCACHEPATH + File.separator +
                "mallnavi_v" + mVersionEntity.version.replace(".", "_") + ".apk";
    }

    private void installApkFileUseSdk(final String apkfile) {
        try {
            final MyManager manager = MyManager.getInstance(this);
            manager.bindAIDLService(UpgradeActivity.this);
            manager.setConnectClickInterface(new MyManager.ServiceConnectedInterface() {
                @Override
                public void onConnect() {
                    manager.silentInstallApk(apkfile, true);
                }
            });
        } catch (Exception e) {
            MToast.showToastMessage("安装失败:" + e.getMessage());
        }
    }

    private void installApkFile(File file) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        Uri uri = null;
        if(Build.VERSION.SDK_INT>= Build.VERSION_CODES.N) {
            uri = FileProvider.getUriForFile(UpgradeActivity.this,
                    PackageUtils.getPackageName(UpgradeActivity.this) + ".fileProvider", file);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        } else {
            uri = Uri.fromFile(file);
        }
        intent.setDataAndType(uri,
                "application/vnd.android.package-archive");
        startActivity(intent);
        finish();
    }

    /**
     * 静默安装apk文件
     * @param apkfile
     */
    private void installApkFileSilent(final String apkfile) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                Process  process = null;
                OutputStream out = null;
                InputStream in = null;
                try {
                    // 请求root
                    process = Runtime.getRuntime().exec("su");
                    out = process.getOutputStream();
                    // 调用安装
                    out.write(("pm install -r " + apkfile + "\n").getBytes());
                    restartApplication(RESTARTAPP_DELAY);
                    in = process.getInputStream();
                    int len = 0;
                    byte[] bs = new byte[256];
                    while (-1 != (len = in.read(bs))) {
                        String state = new String(bs, 0, len);
                        if (state.equals("success\n")) {

                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    try {
                        if (out != null) {
                            out.flush();
                            out.close();
                        }
                        if (in != null) {
                            in.close();
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }

    private static void restartApplication() {
        restartApplication(5000);
    }

    private static void restartApplication(int delay) {
        Context context = Application.get();
        Intent intent = new Intent(context, SplashActivity.class);
        PendingIntent restartIntent = PendingIntent.getActivity(
                context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
        AlarmManager manager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        manager.set(AlarmManager.RTC, System.currentTimeMillis() + delay, restartIntent);
        ActivityManager.get().popupAllActivity();
    }

}